package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.dao.acs.LinkAccountDao;
import cc.linker.steplink.crm.merchant.service.ContentService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.response.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/content")
public class ContentController {

    @Autowired
    private ContentService contentService;

    @Autowired
    private LinkAccountDao linkAccountDao;

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 内容列表
     *
     * @param pageIndex    页码
     * @param pageSize     页面大小
     * @param contentTitle 内容名称
     * @param goodsStatus  商品状态 0 待上架 1 已上架 2 已下架
     * @param goodsType    商品类型1-自有2-联盟
     * @param contentType  内容分类：1.图文2.音频3.视频
     * @param contentGroup 内容分组
     * @param purchase     销售方式1.单独销售2.专栏销售3.混合销售
     */
    @PostMapping("/list")
    public Object list(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        if (ifSales != null && ifSales) {
            // 联盟商家
            String adminId = userinfo.getAdminId();
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            params.put("belongId", customerId);
        } else {
            // 联盟大麦
            params.put("belongId", "");
        }
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        return contentService.getContentList(params);
    }

    /**
     * @param contentId        主键id（新增不传）
     * @param contentTitle     内容标题
     * @param contentCover     内容封面
     * @param contentIntroduce 内容简介
     * @param contentGroup     内容分组
     * @param contentInfo      内容详情
     * @param contentComplete  完整内容
     * @param contentAudition  试看内容
     * @param contentType      内容分类：1.图文2.音频3.视频
     * @param purchase         销售方式1.单独销售2.专栏销售3.混合销售
     * @param goodsId          关联商品id （新增不传）
     * @param resourceId       关联资源id
     * @param columnId         关联专栏id
     * @param moneyAmount      商品价格
     * @param goodsStatus      商品状态 0 待上架 1 已上架 2 已下架
     * @Description: 新增内容
     * @Return: void
     * @Author:ch
     * @Date: 2019/11/21 9:14
     * @Version:
     **/
    @PostMapping("/save")
    public void save(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        params.put("orgId", orgId);
        String customerId = linkAccountDao.getCustomerIdByAdminId(adminId);
        params.put("customerId", customerId);
        contentService.save(params);
    }

    @GetMapping("/copy")
    public void copy(String contentId,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        String customerId = linkAccountDao.getCustomerIdByAdminId(adminId);
        contentService.copy(contentId,orgId,customerId);
    }

    /**
     * @param goodsId     关联商品id
     * @param goodsStatus 商品状态 0 待上架 1 已上架 2 已下架
     * @Description: 内容上下架
     * @Return: void
     * @Author:ch
     * @Date: 2019/11/22 9:53
     * @Version:
     **/
    @PostMapping("/updateStatus")
    public void updateStatus(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Boolean ifSales = userinfo.getSaler();

        if(StringUtils.isEmpty(params.get("goodsId"))){
            throw GlobalException.build("请选择至少一个商品");
        }else{
            String goodsIds = params.get("goodsId").toString();
            String[] split = goodsIds.split(",");
            for(String goodId:split){
                params.put("goodsId",goodId);
                contentService.updateStatus(params, adminId, orgId, ifSales);
            }
        }
    }

    /**
     * @param contentId 主键id
     * @param goodsId   关联商品id
     * @Description: 内容删除
     * @Return: void
     * @Author:ch
     * @Date: 2019/11/22 9:53
     * @Version:
     **/
    @PostMapping("/delete")
    public void delete(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Boolean ifSales = userinfo.getSaler();
        List<Map<String, Object>> param = (List<Map<String, Object>>)params.get("param");
        for(Map<String, Object> pa:param){
            contentService.delete(pa, adminId, orgId, ifSales);
        }
    }

    /**
     * 获取内容列表
     *
     * @param columnId 栏目id
     */
    @PostMapping("/contentList")
    public Object contentList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        if (ifSales != null && ifSales) {
            // 联盟商家
            String adminId = userinfo.getAdminId();
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            params.put("belongId", customerId);
        } else {
            // 联盟大麦
            params.put("belongId", "");
        }
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        return contentService.contentList(params);
    }

    /**
     * 获取内容详情
     *
     * @param contentId 主键id
     */
    @PostMapping("/contentInfo")
    public Object contentInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        if (ifSales != null && ifSales) {
            // 联盟商家
            String adminId = userinfo.getAdminId();
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            params.put("belongId", customerId);
        } else {
            // 联盟大麦
            params.put("belongId", "");
        }
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        Map<String,Object> result = BeanMapUtils.beanToMap(contentService.contentInfo(params));
        // 获取关联的标签
        Long goodsId = contentService.getGoodsIdByContentId(params.get("contentId").toString());
        List<Map<String, Object>> labels = shopGoodsMapper.getGoodsLabelsById(goodsId);
        result.put("labels",labels);
        return result;
    }

    /**
     * 将内容设置为免费
     *
     * @param contentId
     */
    @PostMapping("/setFree")
    public void setFree(@RequestBody Map<String, Object> params) {
        contentService.setFree(params);
    }

    /**
     * 设置序号
     *
     * @param columnId  专栏id
     * @param contentId 内容id
     * @param serialNum 序号
     */
    @PostMapping("/setSerialNum")
    public void setSerialNum(@RequestBody Map<String, Object> params) {
        contentService.setSerialNum(params);
    }


    /**
     * 获取素材中心内容
     * @param session
     * @param pageIndex
     * @param pageSize
     * @param type
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @GetMapping("/getMaterialList")
    public Map<String,Object> getMaterialList(HttpServletRequest request,
                                     @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                     @RequestParam(value = "pageSize", defaultValue = "20", required = false) Integer pageSize,
                                     @RequestParam(value = "type", defaultValue = "-1", required = false) Integer type
                                     ) throws IOException, URISyntaxException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        Map<String,Object> param = new HashMap<>();
        param.put("PageIndex",pageIndex-1);
        param.put("PageSize",pageSize);
        param.put("Type",type);
        param.put("AddressType",1);
        param.put("UserID",adminId);
//        param.put("UserID","e8a8d692-4264-4e85-a6d0-686c352a6a9b");
        param.put("UserIdentity",-1);
        /**
         * 0：音频 1：视频 2：图片 3：图文
         * 图片（image）: 10M，支持PNG\JPEG\JPG\GIF格式
         * 语音（voice）：2M，播放长度不超过60s，支持AMR\MP3格式
         * 视频（video）：10MB，支持MP4格式
         * 缩略图（thumb）：64KB，支持JPG格式
         */
        if(0==type){
            param.put("Size",2047000);
        }
        if(1==type || 2==type){
            param.put("Size",10239000);
        }
        return contentService.getMaterialList(param);
    }


    /**
     * 获取素材详情
     * @param session
     * @param resId
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @GetMapping("/getMaterialDetail")
    public Map getMaterialDetail(String ResId) throws IOException, URISyntaxException {
        return contentService.getMaterialDetail(ResId);
    }

}